#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "sqldb.h"
#include "gameshowwid.h"
#include "gamehall.h"
#include <QJsonDocument>
#include <QJsonObject>

#define Port 7777

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    signal(SIGPIPE,SIG_IGN);

    string createTable="create table user(user_name varchar(20) primary key,"
                       " cipher varchar(20))";
    SqlDb::getInstance()->doSql(createTable);
    while (true)
    {
        client =shared_ptr<SockClient>(new SockClient("127.0.0.1",Port));
        if(client->connectToHost()==-1)
        {
            //超时  你可以在这里设置重传次数
        }
        else
        {
            break;
        }
    }
    client->start();
    wid.setSocket(client);
    //wid.show();

    //令chessshow处于可以进入网络对战的状态---->点击加入房间 但是不给服务端发送信令
    connect(&wid,&GameHall::signal_NetGameStart,[=](){  chess.setNetGameHaveFindHome(true); });

    startReadLoop();
    chess.setNetWork(client);
    //chess.show();

    UserLogin::getInstance()->setSocketClient(client);
    UserLogin::getInstance()->show();
    UserLogin::getInstance()->setGame(&chess);

    connect(&chess,&ChessShow::signal_rollBackLoading,this,&MainWindow::rollBackLoading);
    connect(&chess,&ChessShow::signal_showHall,[=](){  wid.show();});
    connect(this,&MainWindow::signal_HideHall,this,&MainWindow::hideHall);
}

void MainWindow::hideHall()
{
    wid.hide();
}
void MainWindow::rollBackLoading()
{
    chess.hide();
    UserLogin::getInstance()->show();
}

MainWindow::~MainWindow()
{
    client->~SockClient();
    delete ui;
}

void MainWindow::readLoopDispatch()
{
    while (true)
    {
        int len=0;
        int ret=client->stableRecv((char*)&len,4);
        //cout<<"读取到的信息长度"<<len<<endl;
        if(ret>0)
        {
            char *mem=(char*)malloc(len+4);
            memset(mem,0,len+4);

            client->stableRecv(mem,len);
            cout<<"读取到的信息为"<<mem<<" "<<endl;
            QString type=getType(mem);
            cout<<"读取到的信息类型"<<type.toStdString().c_str()<<endl;
            if(type=="First")
            {
                emit chess.signal_First();
                emit signal_HideHall();
            }
            else if(type=="Second")
            {
                emit chess.signal_Second();
                emit signal_HideHall();
            }
            else if(type=="SendChess")
            {
                emit chess.signal_GetChess(QString(mem));
            }
            else if(type=="TimeOut")
            {
                emit chess.signal_PerTimeOut();
            }
            else if(type=="PerWon")
            {
                cout<<"对端赢了"<<mem<<endl;
                emit chess.signal_PerWon();
            }
            else if(type=="PerLeft")
            {
                emit chess.signal_PerLeft();
            }
            else if(type=="TalkToPeer")
            {
                cout<<"gettalking"<<mem<<endl;
                chess.slot_GetTalkToPeer(mem);
            }
            else if(type=="Pong")
            {
                 cout<<"getPong"<<mem<<endl;
            }
            else if(type=="PeerRequestUndo")
            {
                //对端申请悔棋
                emit chess.signal_PeerRequestUndo();
            }
            else if(type=="UndoAgree")
            {
                emit chess.signal_PeerAgreeUndo();
            }
            else if(type=="PeerDisagreeUndo")
            {
                emit chess.signal_PeerDisagreeUndo();
            }
            else if(type=="RefuseFindHouseSuccess")
            {
                emit chess.signal_RefuseFindHomeSuccess();
            }
            else if(type=="RefuseFindHouseFail")
            {
                emit chess.signal_RefuseFindHomeFail();
            }
            else if(type=="FAIL_LOADING")
            {
                emit UserLogin::getInstance()->s_loadFail();
            }
            else if(type=="SUCCESS_LOADING")
            {
                emit UserLogin::getInstance()->s_loadSuccess();
            }
            else if(type=="FAIL_REGIST")
            {
                emit UserLogin::getInstance()->s_registFail();
            }
            else if(type=="SUCCESS_REGIST")
            {
                emit UserLogin::getInstance()->s_registSuccess();
            }
            else if(type=="CreateSeat_Hall_Success")
            {
                emit wid.signal_CreateSeatSuccess();
            }
            else if(type=="CreateSeat_Hall_Fail")
            {
                emit wid.signal_CreateSeatFail();
            }
            else if(type=="HallDetail_Flash")
            {
                emit wid.getDetailHomeInfo(mem);
            }
            else if(type=="JoinSeat_Hall_Success")
            {

            }
            else if(type=="JoinSeat_Hall_Fail")
            {
                emit wid.signal_JoinFail(mem);
            }
            free(mem);
        }
    }
}

void         MainWindow::getHomeDetail(char *mem)
{

}

QByteArray  MainWindow::getType(QByteArray bytearray)
{
    QJsonParseError jsonError;
    QJsonDocument paserDoc = QJsonDocument::fromJson(bytearray,&jsonError);
    if (jsonError.error == QJsonParseError::NoError)
    {
        QJsonObject paserObj = paserDoc.object();
        if (paserObj.contains("type"))
        {
            return paserObj["type"].toString().toStdString().c_str();
        }
    }
    return "";
}

void   MainWindow::startReadLoop()
{
    std::thread th(&MainWindow::readLoopDispatch,this);
    th.detach();
}

